package com.ucar.umock.client;

import com.ucar.umock.client.config.UMockMethodConfigParser;
import com.ucar.umock.client.config.memory.UMockMethodConfigMemoryOperate;
import com.ucar.umock.client.config.UMockMethodConfigOperate;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @ClassName UMockHelper
 * @Description TODO
 * @Author zhanbs baoshan.zhan@ucarinc.com
 * @Date 2020/4/2 16:34
 * @Version 1.0
 **/
@Component
public class UMockHelper implements ApplicationContextAware ,BeanFactoryPostProcessor {

    private static UMockHelper helper;

    private UMockMethodConfigOperate mockMethodConfigOperate;

    private UMockMethodConfigParser umockMethodConfigParser;

    private ApplicationContext applicationContext;


    public static UMockMethodConfigOperate getMockMethodConfigOperate(){
        return helper.mockMethodConfigOperate;
    }
    /**
     * 获取Mock key
     * @param method
     * @return
     */
    public static String getMockMethodConfigKey(Method method){
        String className=method.getDeclaringClass().getName();
        String methodName=method.getName();
        String key=className+"_"+methodName;
        return key;
    }

    public static <T> T getBean(String beanName){
        return (T)helper.applicationContext.getBean(beanName);
    }



    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
       helper=applicationContext.getBean(UMockHelper.class);
    }

    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        mockMethodConfigOperate =new UMockMethodConfigMemoryOperate();
        umockMethodConfigParser =new UMockMethodConfigParser();
        umockMethodConfigParser.parse(configurableListableBeanFactory);
    }
}
